<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Repositories\OrderRepository;
use App\Repositories\OtherOrderRepository;
use App\Repositories\UserRepository;
use App\Repositories\CustomerRepository;
use App\Repositories\ReplyRepository;
use App\Repositories\DepartmentRepository;
use App\Repositories\WebPermissionRepository;
use App\Repositories\LanCompleteRepository;
use App\Repositories\RenewRepository;
use App\Repositories\ContractRepository;
use Carbon\Carbon;
use App\Services\PHPTree;
use App\Http\Requests\StoreOrderRequest;

class OrderController extends AdminController
{
    public function __construct(
        OrderRepository $order, 
        OtherOrderRepository $otherOrder,
        UserRepository $user, 
        CustomerRepository $customer,
        DepartmentRepository $department,
        WebPermissionRepository $webPermission,
        LanCompleteRepository $lanComplete,
        RenewRepository $renew,
        ContractRepository $contract
    )
    {
        $this->order = $order;
        $this->otherOrder = $otherOrder;
        $this->user  = $user;
        $this->customer = $customer;
        $this->department = $department;
        $this->webPermission = $webPermission;
        $this->lanComplete = $lanComplete;
        $this->renew = $renew;
        $this->contract = $contract;
        $this->system = config('system');
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {     
        $condition = $request->except('page');

        if (!$request->has('type')) { $condition['type'] = 1; }

        $where = collect($condition);

        // 导出数据
        if ($where->get('export') == 1) {
            return $this->order->exportExcel($where);
        }

        $data = $this->order->paginateList($where);

        $system = $this->system;
        $designer = $this->user->designerSelect()->toArray();

        if ($condition['type'] == 2) {
            $tpl = 'admin.order.common';
        } else {
            $level = $request->user()->group->level;
            $tpl = ($level != 5) ? 'admin.order.web' : 'admin.order.index';
        }

        $type = $condition['type'];

        // 统计每个进度订单的数量
        $counts = $this->order->progressCounts($type);
        // 特殊订单个数
        $specialCounts = $condition['type'] == 1 ? $this->order->specialCounts() : 0;

        return view($tpl, compact('data', 'system', 'designer', 'where', 'request', 'type', 'counts', 'specialCounts'));
    }

    // 订单管理
    public function getManager(Request $request)
    {
        $condition = $request->except('page');
        $where = collect($condition);
        $system = $this->system;

        $user = $request->user();

        $items = [];
        $tpl = 'manager';

        if ($user->group->level == 3) {
            // 业务员
            $tpl = 'manager-3';
            $where->put('saler_id', $user->id);
        } elseif ($user->group->level == 4) {
            // 业务经理
            $tpl = 'manager-4';
            $where->put('department_id', $user->department_id);

            $items['salers'] = $this->user->salerSelect(['department_id'=>$user->department_id])->prepend('请选择业务员', 0);
        } elseif ($user->group->level == 8) {
            // 总监
            $tpl = 'manager-8';
            $items['departmentsTree'] = (new PHPTree($this->department->all()))->render();
            $items['salers'] = $this->user->getSalersByDepartment(); 

            $where->put('region_id', $user->region_id);
        } else {
            $items['departmentsTree'] = (new PHPTree($this->department->all()))->render();
            $items['salers'] = $this->user->getSalersByDepartment();
        }

        // 导出数据
        if ($where->get('export') == 1) {
            return $this->order->exportManagerExcel($where);
        }
       
        $items['system'] = $this->system;
        $items['where']  = $where;
        $items['data']   = $this->order->paginateList($where);

        return view('admin.order.'.$tpl, $items);
    }

    // 业务/经理/总监，自己名下的订单
    public function myorder(Request $request)
    {  
        // 当前用户
        $user = auth()->user();

        $condition = $request->except('page');

        if (!$request->has('type')) { 
            $condition['type'] = 1; 
        }

        $where = collect($condition);

        // 去除空的条件
        $filterWhere = $where->filter(function ($item) {
            return $item;
        });

        $data = $this->order->myPaginate($filterWhere);
        $system = $this->system;

        // 统计每个进度订单的数量
        $counts = $this->order->myProgressCounts($request->get('type', 1), $user->id);  

        $tpl = $condition['type'] == 2 ? 'admin.order.myorder_common' : 'admin.order.myorder';

        return view($tpl, compact('data', 'system', 'where', 'user', 'counts', 'request'));
    }

    // 我的录入
    public function myInput(Request $request)
    {
        // 当前用户
        $user = auth()->user();

        $condition = $request->all();

        if (!$request->has('type')) { 
            $condition['type'] = 1; 
        }

        $where = collect($request->all());

        $data = $this->order->myInputPaginate($where);
        $system = $this->system;

        // 统计录入进度数量
        $counts = $this->order->myInputProgressCounts($user->id);       

        return view('admin.order.myinput', compact('data', 'system', 'counts', 'where', 'user', 'request'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create(Request $request)
    {
        $tpl = 'admin.order.order_add';

        $type = 1;

        if ($request->input('type') == 2) {
            $tpl = 'admin.order.common_add';
            $type = 2;
        }

        $languages = $this->system['language'];

        return view($tpl, compact('languages', 'type'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(StoreOrderRequest $request)
    {
        $customerName = $request->input('customer');

        // 添加客户
        $customer = $this->customer->findBy('name', $customerName);

        if (!$customer) {
            // 添加客户信息
            $customer = $this->customer->create([
                'name'           => $customerName,
                'contact_people' => $request->input('contact_people'),
                'phone'          => $request->input('phone'),
                'tel'            => $request->input('tel'),
                'fax'            => $request->input('fax'),
                'city'           => $request->input('city'),
                'detail_address' => $request->input('detail_address'),
                'domain'         => $request->input('domain'),
                'email'          => $request->input('email'),
                'saler_id'       => $request->input('saler_id'),
            ]);
        }

        $data = $request->except('customer', 'languages', 'referer');

        $data['cid']     = $customer->id;               // 客户信息ID
        $data['sn']      = makeOrderNumber();           // 订单号

        // 检查合同完整性
        $data['contract_no'] && ($this->contract->checkFull($data['contract_no'], $customer->id));

        $result = $this->order->create($data);

        if ($result) {

            // 添加语言版本
            if (!empty($request->input('languages'))) {
                $this->lanComplete->multiCreate($result->id, $request->input('languages'));
            }

            $referer = $request->input('referer');
            $goto = $referer ? redirect($referer) : back();

            return $goto->with('success', '您的订单提交成功');
        }

        return back()->with('error', '对不起，下单失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show(Request $request, $id, ReplyRepository $reply)
    {
        $user = $request->user();
        $data = $this->order->find($id);

        if (!$data) {
            return abort(404, '该订单不存在！');
        }

        // 判断该用户是否该订单的拥有者
        $this->user->owner($data->saler_id, $user, '您没有权限查看该订单。');

        $lans = config('system.language');

        $u = $request->input('u', 0);

        return view('admin.order.show', compact('data', 'lans', 'user', 'u'));   
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit(Request $request, $id)
    {
        $data = $this->order->find($id);
        $designers = $this->user->designerSelect();
        $type = $data->type;

        $u = $request->input('u', 0);

        $tpl = $type == 2 ? 'admin.order.common_edit' : 'admin.order.order_edit';

        return view($tpl, compact('data', 'designers', 'tpl', 'u'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->except('customer', 'referer');

        // 判断是否加急
        if (!isset($data['expedited'])) { 
            $data['expedited'] = 0; 
        }

        $referer = $request->input('referer');
        $goto = $referer ? redirect($referer) : back();

        $order = $this->order->find($id);

        if (!$order) {
            return $goto->with('error', '订单更新失败');
        }

        // 检查合同完整性
        if ($data['contract_no']) {
            $this->contract->checkFull($data['contract_no'], $order->cid);
        }

        // 删除架构站对应的设计师
        if ($data['product'] == 2) {
            $data['designer_id'] = 0;
        }

        $result = $order->fill($data)->save();

        if ($result) {
            return $goto->with('success', '订单更新成功');
        }

        return $goto->with('error', '订单更新失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $renew = $this->renew->findBy('order_id', $id);

        if ($renew) {
            flash('error', '此订单已经续费，不允许删除');
            return response()->json(['code' => 500]);      
        }

        $result = $this->order->delete($id);

        if ($result) {
            flash('success', '订单删除成功');
            return response()->json(['code' => 200]);
        }

        flash('error', '订单删除失败');
        return response()->json(['code' => 500]);
    }

    // 统计订单进度
    public function progressTongji(Request $request)
    { 
        $range = [
            'start' => $request->get('start') ?: Carbon::now()->startOfMonth()->format('Y-m-d'),
            'end'   => $request->get('end') ?: Carbon::now()->endOfMonth()->format('Y-m-d')
        ];

        return view('admin.order.tongji', compact('range'));
    }

    public function countPart($part, Request $request)
    {
        switch ($part) {
            case 'web':
                $data = $this->webCountPeriod($request);
                break;
            case 'other':
                $data = $this->otherCountPeriod($request);
                break;
            case 'detail':
                $data = $this->detailCountPeriod($request);
                break; 
            case 'team':
                $data = $this->teamCount($request);
                break; 
            default:
                # code...
                break;
        }

        return response()->json([
            'data' => $data,
            'status' => ['code'=>200, 'msg'=>'加载成功']
        ]);
    }

    // 网站统计明细
    protected function detailCountPeriod(Request $request)
    {
        $range = $this->simpleDateRange($request->get('start'), $request->get('end'));
        $cacheKey = md5($range['start'].$range['end']);

        $data = \Cache::remember($cacheKey, 10, function() use ($range) {
            return $this->order->getDetailCountPeriod($range);
        }); 

        return $data;

        // return $this->order->getDetailCountPeriod($range);
    }

    // 小组订单完成情况统计
    protected function teamCount(Request $request)
    {
        $range = $this->simpleDateRange($request->get('start'), $request->get('end')); 

        return $this->order->getTeamCount($range);
    }

    // 网站统计
    protected function webCountPeriod(Request $request)
    {
        $range = $this->simpleDateRange($request->get('start'), $request->get('end'));

        return $this->order->getWebCountPeriod($range);
    }

    // 其他订单统计
    public function otherCountPeriod(Request $request)
    {
        $range = $this->simpleDateRange($request->get('start'), $request->get('end'));

        return $this->otherOrder->getOtherCountPeriod($range);  
    }

    protected function simpleDateRange($start, $end)
    {
        $range = [
            'start' => $start ?: Carbon::now()->startOfMonth()->format('Y-m-d'),
            'end'   => $end ?: Carbon::now()->endOfMonth()->format('Y-m-d')
        ];

        return [
            'start' => Carbon::createFromFormat('Y-m-d', $range['start'])->startOfDay(),
            'end'   => Carbon::createFromFormat('Y-m-d', $range['end'])->endOfDay(),
        ]; 
    }

    // 网站订单权限
    public function getWebPermission($id)
    {
        $order = $this->order->find($id);
        $permission = $this->webPermission->findBy('order_id', $id);

        return view('admin.order.web_permission', compact('order', 'permission'));       
    }

    // 
    public function postWebPermission(Request $request, $id)
    {
        $result = $this->webPermission->updatePermission($request->except('_token'), $id);

        if ($result) {
            return back()->with('success', ' 网站权限更新成功'); 
        }

        return back()->with('error', ' 网站权限更新失败');
    }

    // 订单导入
    public function import()
    {
        $file = 'data/import/1.xlsx';

        $result = $this->order->import($file);

        return $result;
    }

    // 订单设置标签
    public function tag(Request $request, $id)
    {
        $tag = $request->input('tag');
        return $this->order->update(['tag'=>$tag], $id);
    }

    // 修复订单状态
    public function repair()
    {
        $result = $this->order->repair();

        if ($result) {
            return back()->with('success', ' 订单修复成功'); 
        }

        return back()->with('error', ' 订单修复失败');
    }

}
